package com.sunrise.gateway.web.servlet;

import com.dap.exception.ErrorCodeContainer;
import com.dap.exception.PlatformException;
import com.sunrise.gateway.commons.CommonUtils;
import com.sunrise.gateway.commons.Result;
import com.sunrise.gateway.web.core.OSSEngineBase;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public abstract class OSSServletBase extends ServletBase {
    protected OSSEngineBase engine;

    @Override
    protected void doMyPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String code;
        String message = null;
        List<String> data = null;
        try {
            data = engine.execute(req, resp);
            code = com.dap.commons.Constants.ResponseCode.SYS_SUCCESS;
        } catch (Exception e) {
            LOGGER.error("", e);
            if (e instanceof PlatformException) {
                //返回业务异常
                code = ((PlatformException) e).getErrorCode();
                message = ((PlatformException) e).getErrorMessage();
                if (StringUtils.isEmpty(message)) {
                    message = "文件上传异常";
                }
            } else {
                //返回系统异常
                code = com.dap.commons.Constants.ResponseCode.SYS_ERROR;
            }
        }
        if (StringUtils.isEmpty(message)) {
            message = ErrorCodeContainer.getErrorMessage(code);
        }

        Result result = new Result(code, message, data);
        CommonUtils.writeStrIntoResponse(result.toJsonString(), resp);
    }

}
